using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.Xna.Framework;
using CreamX.Core.TileMap;



namespace CreamX.Framework.Game
{
    public class PathFindindGrid:ICloneable
    {
        public int TilesX;
        public int TilesY;
        public Vector2 TileDisplaySize;

        public bool[,] clear;

        public CreamXObject[,] tile;
        public List<uint> _ignoreList;

       // public CreamXTileSet Owner;

        public bool IsTileClear(TileMapLocation tile)
        {
            if (tile.X<0 || tile.Y<0 || tile.X > clear.GetUpperBound(0) ||
                tile.Y > clear.GetUpperBound(1) )
                return true;
            return clear[tile.X, tile.Y];
        }

        /// <summary>
        /// Determines if path between two screen locations is blocked.
        /// </summary>
        /// <param name="startLocation">Starting screen location</param>
        /// <param name="endLocation">Ending screen location</param>
        /// <returns>True if a fixed object is in a tile between the two locations</returns>
        public bool PathBlocked(Vector2 startLocation, Vector2 endLocation)
        {
            TileMapLocation tile = GetTile(startLocation);
            TileMapLocation endTile = GetTile(endLocation);

            // Compute vector between start and end locations.
            Vector2 location = GetTileCenter(tile);
            Vector2 delta = GetTileCenter(endTile) - location;
            delta.Normalize();

            // Test every tile between the two locations.
            while ((!tile.Equals(endTile)) && (IsTileClear(tile)))
            {
                TileMapLocation nextTile;
                do
                {
                    location += delta;
                    nextTile = GetTile(location);
                } while (nextTile.Equals(tile));

                tile = nextTile;
            }

            return (!IsTileClear(tile));
        }
        
        public Vector2 GetTileCenter(TileMapLocation tile)
        {
            return new Vector2(
                        TileDisplaySize.X * tile.X + TileDisplaySize.X / 2,
                        TileDisplaySize.Y * tile.Y + TileDisplaySize.Y / 2);
        }

        public TileMapLocation GetTile(Vector2 screenLocation)
        {
            TileMapLocation tile;
            tile.X = (int)(screenLocation.X / TileDisplaySize.X);
            tile.Y = (int)(screenLocation.Y / TileDisplaySize.Y);
            return tile;
        }

        #region ICloneable Members

        public object Clone()
        {
            return MemberwiseClone();
        }

        #endregion
    }


}
